<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Products;
use App\Services\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class CollectionController extends Controller
{
    /**
     * 用户收藏商品列表
     */
    public function product(Request $request)
    {
        $page = $request->input('page', 1) ?: 1;
        $limit = $request->input('limit', 10) ?: 10;

        $skip = ($page - 1) * $limit;

        $query = Auth::user()->collections()->latest();

        $products = $query->skip($skip)->limit($limit)->get();

        return Api::success(Products::collection($products));
    }

    /**
     * 添加收藏
     */
    public function attach(Request $request)
    {
        $id = $request->input('product_id');

        Auth::user()->collections()->attach($id);

        return Api::success();
    }

    /**
     * 取消收藏
     */
    public function detach(Request $request)
    {
        $id = $request->input('product_id', 0);

        if ($id) {
            Auth::user()->collections()->detach($id);
        } else {
            Auth::user()->collections()->detach();
        }

        return Api::success();
    }
}
